package com.gang.ssm.bos.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gang.ssm.bos.common.Page;
import com.gang.ssm.bos.system.bean.Workordermanage;
import com.gang.ssm.bos.system.mapper.WorkordermanageMapper;
import com.gang.ssm.bos.system.service.WorkordermanageService;

@Service
public class WorkordermanageServiceImpl implements WorkordermanageService{

	@Autowired
	private WorkordermanageMapper workordermanageMapper;
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private HistoryService historyService;
	
	@Override
	public void pageQuery(Page<Workordermanage> pageBean) {
		int total = (int) workordermanageMapper.countByNoStart();
		List<Workordermanage> workordermanages = workordermanageMapper.findNoStartByLimit((pageBean.getPageNo() - 1) * 
				pageBean.getPageSize(),pageBean.getPageSize());
		
		pageBean.setTotalCount(total);
		pageBean.setResult(workordermanages);
	}

	@Override
	public void save(Workordermanage workordermanage) {
		workordermanageMapper.insertSelective(workordermanage);
	}

	@Override
	public List<Workordermanage> findNoStart() {
		return workordermanageMapper.findNoStart();
	}

	@Override
	public void start(Integer id) {
		Workordermanage workordermanage = workordermanageMapper.selectByPrimaryKey(id);
		workordermanageMapper.updateStartTo1(id);
		String processDefinitionKey = "transfer";
		String businessKey = id.toString();
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("业务数据", workordermanage);
		runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);
	}

	@Override
	public Workordermanage findById(Integer id) {
		return workordermanageMapper.selectByPrimaryKey(id);
	}

	@Override
	public void checkWorkordermanage(String taskId, Integer check,
			String workordermanageId) {
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		String processInstanceId = task.getProcessInstanceId();
		
		Map<String, Object> map = new HashMap<>();
		map.put("check", check);
		taskService.complete(taskId, map);
		
		if(check == 0) {
			workordermanageMapper.updateStartTo0(Integer.valueOf(workordermanageId));
			historyService.deleteHistoricProcessInstance(processInstanceId);
		}
	}

}
